<template>
  <!-- 部门消费统计 -->
  <div class="department_consumption">
    <el-form :inline="true" :model="elform" class="demo-form-inline" size="mini">
      <!-- <el-form-item label="人员:" label-width="40px" id="elfrom1">
        <el-input v-model="userName" placeholder="名称" size="mini" clearable></el-input>
      </el-form-item>-->
      <!-- 时间控件 -->
      <myTime @handleGetTime="handleGetTime"></myTime>
      <el-form-item label="部门:">
        <el-select v-model="departmentGuid" placeholder="请选择" size="mini" clearable multiple>
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="餐别分类显示:" v-if="activeName == 'first' ? true : false">
        <el-checkbox v-model="mealFlag"></el-checkbox>
      </el-form-item>
      <el-form-item class="searchmarigin">
        <el-button
          type="primary"
          @click="onSubmit"
          size="mini"
          icon="el-icon-search"
          v-if="activeName == 'first' ? true : false"
        >查询</el-button>
        <el-button
          type="primary"
          @click="DetailsonSubmit"
          size="mini"
          icon="el-icon-search"
          v-if="activeName == 'second' ? true : false"
        >查询</el-button>

        <el-button
          type="primary"
          @click="onExport"
          size="mini"
          icon="el-icon-document-copy"
          v-if="activeName == 'first' ? true : false"
        >导出</el-button>
        <el-button
          type="primary"
          @click="onExport('print')"
          size="mini"
          icon="el-icon-printer"
          v-if="activeName == 'first' ? true : false"
        >打印</el-button>
        <el-button
          type="primary"
          @click="DetailsonExport"
          size="mini"
          icon="el-icon-document-copy"
          v-if="activeName == 'second' ? true : false"
        >导出</el-button>
        <el-button
          type="primary"
          @click="DetailsonExport('print')"
          size="mini"
          icon="el-icon-printer"
          v-if="activeName == 'second' ? true : false"
        >打印</el-button>
      </el-form-item>
      <el-form-item v-if="activeName == 'first' ? true : false">
        <el-popover width="700" placement="top" trigger="click">
          <el-row>
            <el-row>
              <el-col :span="6" v-for="item in Object.keys(formThead)" :key="item">
                <el-checkbox
                  :label="formThead[item].label"
                  v-model="formThead[item].checked"
                  @change="checkboxChanged()"
                ></el-checkbox>
              </el-col>
            </el-row>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
      <el-form-item v-if="activeName == 'second' ? true : false">
        <el-popover width="500" placement="top" trigger="click">
          <el-row>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.cardNumber.label"
              v-model="formThead2.cardNumber.checked"
              @change="checkboxChanged2()"
              margin-right:10px
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.departmentName.label"
              v-model="formThead2.departmentName.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.userName.label"
              v-model="formThead2.userName.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.dataMakeTime.label"
              v-model="formThead2.dataMakeTime.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
          </el-row>
          <el-row>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.expenditure.label"
              v-model="formThead2.expenditure.checked"
              @change="checkboxChanged2()"
              margin-right:10px
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.newBalance.label"
              v-model="formThead2.newBalance.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.chargingType.label"
              v-model="formThead2.chargingType.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.consumePlace.label"
              v-model="formThead2.consumePlace.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
          </el-row>
          <el-row>
            <el-checkbox
              style="width: 10%"
              :label="formThead2.terminalCode.label"
              v-model="formThead2.terminalCode.checked"
              @change="checkboxChanged2()"
            ></el-checkbox>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tabs_main">
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="部门消费汇总" name="first">
          <el-table
            ref="table"
            :data="summarydata"
            border
            highlight-current-row
            row-key="id"
            :tree-props="{
              children: 'mealConsumeDataList',
              hasChildren: 'hasChildren',
            }"
            :header-cell-style="headFirst"
            style="width: 100%"
            v-loading="loading"
            :cell-style="
              mealFlag ? () => {} : (res) => headFirst_col(res, summarydata)
            "
          >
            <el-table-column
              prop="departmentName"
              label="部门名称"
              v-if="formThead.departmentName.checked"
              min-width="120px"
            ></el-table-column>
            <el-table-column prop="mealName" label="餐别" v-if="formThead.mealName.checked"></el-table-column>
            <el-table-column prop="consumeCount" label="消费次数" v-if="formThead.consumeCount.checked"></el-table-column>
            <el-table-column prop="userCount" label="消费人次" v-if="formThead.userCount.checked"></el-table-column>
            <el-table-column
              prop="minExpenditure"
              label="最小操作金额(元)"
              width="100px"
              v-if="formThead.minExpenditure.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.minExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="maxExpenditure"
              label="最大操作金额(元)"
              width="120px"
              v-if="formThead.maxExpenditure.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.maxExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>

            <el-table-column
              prop="avgExpenditure"
              width="130px"
              label="平均操作金额(按次数)"
              v-if="formThead.avgExpenditure.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.avgExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              width="170"
              prop="avgUserExpenditure"
              label="平均操作金额(按人数)"
              v-if="formThead.avgUserExpenditure.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.avgUserExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="sumExpenditure"
              label="合计(元)"
              v-if="formThead.sumExpenditure.checked"
              min-width="120px"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.sumExpenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="timesExpenditureCount"
              label="计次消费次数"
              v-if="formThead.timesExpenditureCount.checked"
              width="90px"
            ></el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChangepage"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordCount"
            ></el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="消费明细" name="second">
          <el-table
            v-loading="loading2"
            :data="detailslist"
            border
            highlight-current-row
            style="width: 100%"
            :header-cell-style="headFirst"
            :cell-style="
              detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
            "
            ref="detailslist"
          >
            <el-table-column
              prop="cardNumber"
              label="卡号"
              v-if="formThead2.cardNumber.checked"
              width="120px"
            ></el-table-column>
            <el-table-column prop="userName" label="姓名" v-cloak v-if="formThead2.userName.checked"></el-table-column>
            <el-table-column
              prop="departmentName"
              label="部门名称"
              v-cloak
              v-if="formThead2.departmentName.checked"
            ></el-table-column>
            <el-table-column
              prop="dataMakeTime"
              label="消费时间"
              v-cloak
              v-if="formThead2.dataMakeTime.checked"
              min-width="160px"
            ></el-table-column>
            <el-table-column
              prop="expenditure"
              label="操作金额(元)"
              v-cloak
              v-if="formThead2.expenditure.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.expenditure | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="newBalance"
              label="卡内余额(元)"
              v-cloak
              v-if="formThead2.newBalance.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.newBalance | amountyuan }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="chargingType"
              label="交易类型"
              v-if="formThead2.chargingType.checked"
            >
              <template slot-scope="scope">
                <div>{{ scope.row.chargingType | filterchargingType }}</div>
              </template>
            </el-table-column>
            <el-table-column
              prop="consumePlace"
              label="消费地点"
              v-cloak
              v-if="formThead2.consumePlace.checked"
            ></el-table-column>
            <el-table-column
              prop="terminalCode"
              label="设备编号"
              v-cloak
              v-if="formThead2.terminalCode.checked"
            ></el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChangepage2"
              :current-page="currentPage2"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="recordCount2"
            ></el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      //查询合计
      totalist: {},
      //导出合计
      exporttotalist: {},
      exporttotalistArr: [],
      elform: {},
      departmentGuid: [],
      userName: '',
      departmentoptions: [],
      daytime: '',
      time: '',
      loading: false,
      loading2: false,
      activeName: 'first',
      exportflag: true,
      searchInfo: {},
      //汇总报表
      summarydata: [],
      pageSize: 20,
      pageNum: 1,
      currentPage: 1,
      recordCount: 0,
      mealFlag: false,
      placeFlag: false,
      summaryExportlist: [],
      formThead: {
        departmentName: {
          label: '部门名称',
          prop: 'departmentName',
          checked: true
        },
        mealName: { label: '餐别', prop: 'mealName', checked: true },
        consumeCount: {
          label: '操作次数',
          prop: 'consumeCount',
          checked: true
        },
        userCount: { label: '操作人数', prop: 'userCount', checked: true },
        minExpenditure: {
          label: '最小操作金额(元)',
          prop: 'minExpenditure',
          checked: true
        },
        maxExpenditure: {
          label: '最大操作金额(元)',
          prop: 'maxExpenditure',
          checked: true
        },
        avgExpenditure: {
          label: '平均操作金额(按次数)',
          prop: 'avgExpenditure',
          checked: true
        },
        avgUserExpenditure: {
          label: '平均操作金额(按人数)',
          prop: 'avgUserExpenditure',
          checked: true
        },
        sumExpenditure: {
          label: '合计(元)',
          prop: 'sumExpenditure',
          checked: true
        },
        timesExpenditureCount: {
          label: '计次消费次数',
          prop: 'timesExpenditureCount',
          checked: true
        }
      },
      filename: '部门消费汇总',
      //消费明细表
      detailsTotal: null,
      detailslist: [],
      pageSize2: 20,
      pageNum2: 1,
      currentPage2: 1,
      recordCount2: 0,
      detailslistExportlist: [],
      formThead2: {
        cardNumber: { label: '卡号', prop: 'cardNumber', checked: true },
        departmentName: {
          label: '部门名称',
          prop: 'departmentName',
          checked: true
        },
        userName: { label: '姓名', prop: 'userName', checked: true },
        dataMakeTime: {
          label: '消费时间',
          prop: 'dataMakeTime',
          checked: true
        },
        expenditure: {
          label: '操作金额(元)',
          prop: 'expenditure',
          checked: true
        },
        newBalance: {
          label: '卡内余额(元)',
          prop: 'newBalance',
          checked: true
        },
        chargingType: {
          label: '交易类型',
          prop: 'chargingType',
          checked: true
        },
        consumePlace: {
          label: '消费地点',
          prop: 'consumePlace',
          checked: true
        },
        terminalCode: {
          label: '设备编号',
          prop: 'terminalCode',
          checked: true
        }
      },
      filename2: '部门消费明细报表'
    }
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  created() {
    this.daytime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
  },
  mounted() {
    this.departmentselectlist()
  },
  methods: {
    handleGetTime(val) {
      this.daytime = [val.startDate, val.endDate]
      this.time = [val.startTime, val.endTime]
      this.radio = val.timeradio
    },
    // 部门选择数据
    departmentselectlist() {
      this.departmentoptions = []
      this.$http({
        url: this.$http.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentoptions.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    /**
     *  部门消费汇总模块
     */
    // 部门消费汇总合计
    departmentgathertotal() {
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-data-department-gather-total'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              _this.totalist = {
                ...data.messageContent,
                departmentName: '合计：',
                mealName: ''
              }
              if (_this.mealFlag == false) {
                let newobj = {
                  ...data.messageContent,
                  departmentName: '合计：',
                  mealName: ''
                }
                _this.exporttotalist.departmentName = newobj.departmentName
                _this.exporttotalist.mealName = newobj.mealName
                _this.exporttotalist.consumeCount = newobj.consumeCount
                _this.exporttotalist.userCount = newobj.userCount
                _this.exporttotalist.timesExpenditureCount =
                  newobj.timesExpenditureCount
                _this.exporttotalist.minExpenditure = _this.amountyua(
                  newobj.minExpenditure
                )
                _this.exporttotalist.maxExpenditure = _this.amountyua(
                  newobj.maxExpenditure
                )
                _this.exporttotalist.avgExpenditure = _this.amountyua(
                  newobj.avgExpenditure
                )
                _this.exporttotalist.avgUserExpenditure = _this.amountyua(
                  newobj.avgUserExpenditure
                )
                _this.exporttotalist.sumExpenditure = _this.amountyua(
                  newobj.sumExpenditure
                )
              }
              if (_this.mealFlag == true) {
                let newArr = []
                let itemobj = JSON.parse(JSON.stringify(data.messageContent))
                newArr.push(itemobj)
                if (itemobj.mealConsumeDataList.length != 0) {
                  for (var i = 0; i < itemobj.mealConsumeDataList.length; i++) {
                    newArr.push(itemobj.mealConsumeDataList[i])
                  }
                }
                _this.exporttotalistArr = newArr
                for (var i = 0; i < _this.exporttotalistArr.length; i++) {
                  _this.exporttotalistArr[i].minExpenditure = _this.amountyua(
                    _this.exporttotalistArr[i].minExpenditure
                  )
                  _this.exporttotalistArr[i].maxExpenditure = _this.amountyua(
                    _this.exporttotalistArr[i].maxExpenditure
                  )
                  _this.exporttotalistArr[i].avgExpenditure = _this.amountyua(
                    _this.exporttotalistArr[i].avgExpenditure
                  )
                  _this.exporttotalistArr[
                    i
                  ].avgUserExpenditure = _this.amountyua(
                    _this.exporttotalistArr[i].avgUserExpenditure
                  )
                  _this.exporttotalistArr[i].sumExpenditure = _this.amountyua(
                    _this.exporttotalistArr[i].sumExpenditure
                  )
                }
              }
              resolve(_this.exporttotalist)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 部门消费汇总分页
    departmentgather() {
      this.searchInfo.unitGuid = this.changeschoolid
      this.loading = true
      this.$http({
        url: this.$http.adornUrl(
          '/terminal/consume/consume-data-department-gather'
        ),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (data.messageCode == 200) {
          if (
            data.messageContent.data.length == 0 ||
            data.messageContent.data == null
          ) {
            this.$message({
              message: '查询成功当前暂无数据',
              type: 'success'
            })
          }
          this.summarydata = data.messageContent.data
          this.summarydata.push(this.totalist)
          //  if(this.mealFlag==true){
          //     this.summarydata.push(this.totalist)
          //  }
          if (this.mealFlag == true) {
            for (var i = 0; i < this.summarydata.length; i++) {
              this.summarydata[i].id = [i].toString()
              if (
                this.summarydata[i].mealConsumeDataList != null &&
                this.summarydata[i].mealConsumeDataList.length != 0
              ) {
                for (
                  var j = 0;
                  j < this.summarydata[i].mealConsumeDataList.length;
                  j++
                ) {
                  this.summarydata[i].mealConsumeDataList[j].id =
                    'k' + i.toString() + j.toString()
                }
              }
            }
          }
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 部门消费查询
    async onSubmit() {
      this.pageNum = 1
      this.exportflag = true
      this.searchInfo = {}
      this.searchInfo.unitGuid = this.changeschoolid
      if (this.departmentGuid != '') {
        this.searchInfo.departmentGuidList = this.departmentGuid
      }
      if (this.userName != '') {
        this.searchInfo.userName = this.userName
      }
      // if (this.daytime != null) {
      //   this.searchInfo.startDate = this.daytime[0];
      //   this.searchInfo.endDate = this.daytime[1];
      // }
      // if (this.time != null) {
      //   this.searchInfo.startTime = this.time[0];
      //   this.searchInfo.endTime = this.time[1];
      // }
      this.searchInfo.startTime = this.daytime[0] + ' ' + this.time[0]
      this.searchInfo.endTime = this.daytime[1] + ' ' + this.time[1]
      this.searchInfo.mealFlag = this.mealFlag
      await this.departmentgathertotal()
      this.departmentgather()
    },
    //部门消费汇总导出或打印
    async onExport(type) {
      if (this.recordCount == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecelinit()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    //部门消费汇总导出
    outexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-data-department-gather'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                asc: true,
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo,
                sortName: _this.sortName
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.summaryExportlist = data.messageContent.data
              // if (_this.searchInfo.mealFlag == false) {
              let arr = [
                'minExpenditure',
                'maxExpenditure',
                'avgExpenditure',
                'avgUserExpenditure',
                'sumExpenditure'
              ]
              _this.summaryExportlist.map(item => {
                arr.map(key => {
                  item[key] = _this.amountyua(item[key])
                })
              })
              _this.summaryExportlist.push(_this.exporttotalist)
              // }
              /**
                else {
                  let newARR = [];
                  for (var i = 0; i < _this.summaryExportlist.length; i++) {
                    newARR.push(_this.summaryExportlist[i]);
                    if (_this.summaryExportlist[i].mealConsumeDataList.length != 0) {
                      for (
                        var j = 0;
                        j < _this.summaryExportlist[i].mealConsumeDataList.length;
                        j++
                      ) {
                        newARR.push(_this.summaryExportlist[i].mealConsumeDataList[j]);
                      }
                    }
                  }
                  for (var i = 0; i < newARR.length; i++) {
                    newARR[i].minExpenditure = _this.amountyua(
                      newARR[i].minExpenditure
                    );
                    newARR[i].maxExpenditure = _this.amountyua(
                      newARR[i].maxExpenditure
                    );
                    newARR[i].avgExpenditure = _this.amountyua(
                      newARR[i].avgExpenditure
                    );
                    newARR[i].avgUserExpenditure = _this.amountyua(
                      newARR[i].avgUserExpenditure
                    );
                    newARR[i].sumExpenditure = _this.amountyua(
                      newARR[i].sumExpenditure
                    );
                  }
                  Array.prototype.push.apply(newARR, _this.exporttotalistArr);
                  _this.summaryExportlist = newARR;
                }
              */
              // setTimeout(() => {
              //   _this.export2Excel();
              // }, 100);
              resolve(_this.summaryExportlist)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 打印
    printJS() {
      let someJSONdata = this.summaryExportlist
      const title = '部门消费汇总表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getDepartmentIsPrint()
      filterValArr.map((item, index) => {
        properties.push({
          displayName: tHeader[index],
          field: filterValArr[index]
        })
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 拿到表头数据
    getDepartmentIsPrint() {
      const filterValArr = [
        'departmentName',
        'mealName',
        'consumeCount',
        'userCount',
        'minExpenditure',
        'maxExpenditure',
        'avgExpenditure',
        'avgUserExpenditure',
        'sumExpenditure',
        'timesExpenditureCount'
      ]
      let valArr = []
      let tHeader = []
      filterValArr.map(item => {
        if (this.formThead[item].checked) {
          valArr.push(this.formThead[item].prop)
          tHeader.push(this.formThead[item].label)
        }
      })
      return { filterValArr: valArr, tHeader }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 导出
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { tHeader, filterValArr } = this.getDepartmentIsPrint()
        const filterVal = filterValArr
        const list = this.summaryExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },
    /** 部门汇总分页 */
    handleSizeChange(val) {
      this.pageSize = val
      this.departmentgather()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.departmentgather()
    },
    checkboxChanged() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    /**
     *  部门消费明细模块
     */
    // 消费明细合计数据获取
    getTotal() {
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl(
              '/terminal/consume/consume-details-total'
            ),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              resolve(data.messageContent)
            } else {
              reject(data.errorMessage)
              this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 消费明细分页数据获取
    consumedetails() {
      this.searchInfo.unitGuid = this.changeschoolid
      this.loading2 = true
      this.$http({
        url: this.$http.adornUrl('/terminal/consume/consume-details-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum2,
            pageSize: this.pageSize2,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading2 = false
        if (data.messageCode == 200) {
          if (
            data.messageContent.data.length == 0 ||
            data.messageContent.data == null
          ) {
            this.$message({
              message: '查询成功当前暂无数据',
              type: 'success'
            })
          }
          this.detailslist = data.messageContent.data
          this.recordCount2 = data.messageContent.recordCount
          this.currentPage2 = data.messageContent.pageNum
          if (this.detailslist.length != 0) {
            this.detailslist.push({ ...this.detailsTotal, newBalance: '' })
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    // 消费明细分页查询
    async DetailsonSubmit() {
      this.pageNum2 = 1
      this.searchInfo = {}
      this.searchInfo.unitGuid = this.changeschoolid
      if (this.departmentGuid != '') {
        this.searchInfo.departmentGuidList = this.departmentGuid
      }
      if (this.userName != '') {
        this.searchInfo.userName = this.userName
      }
      // if (this.daytime != null) {
      //   this.searchInfo.startDate = this.daytime[0];
      //   this.searchInfo.endDate = this.daytime[1];
      // }
      // if (this.time != null) {
      //   this.searchInfo.startTime = this.time[0];
      //   this.searchInfo.endTime = this.time[1];
      // }
      this.searchInfo.startTime = this.daytime[0] + ' ' + this.time[0]
      this.searchInfo.endTime = this.daytime[1] + ' ' + this.time[1]
      this.searchInfo.mealFlag = this.mealFlag
      this.searchInfo.placeFlag = this.placeFlag
      this.detailsTotal = null
      this.detailsTotal = await this.getTotal()
      this.consumedetails()
    },
    // 消费明细导出或打印
    async DetailsonExport(type) {
      if (this.detailslist.length == 0) {
        // if (this.summarydata.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
        // }
        if (this.exportflag == false) {
          this.$message({
            message: '查询条件已经改变请重新查询后导出',
            type: 'warning'
          })
          return false
        }
      }
      // 获取部门消费明细所有数据
      await this.Detailoutexecelinit()
      if (type == 'print') {
        this.printDetailex()
      } else {
        this.Detailexport2Excel()
      }
    },
    // 获取部门消费明细所有数据
    Detailoutexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/terminal/consume/consume-details-page'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount2,
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent.data
              if (_this.detailslistExportlist.length != 0) {
                _this.detailslistExportlist.push({
                  ..._this.detailsTotal,
                  newBalance: ''
                })
              }
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[
                  i
                ].chargingType = _this.filterchargingType(
                  _this.detailslistExportlist[i].chargingType
                )
                _this.detailslistExportlist[i].expenditure = _this.amountyua(
                  _this.detailslistExportlist[i].expenditure
                )
                _this.detailslistExportlist[i].newBalance = _this.amountyua(
                  _this.detailslistExportlist[i].newBalance
                )
              }
              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    // 拿到部门消费明细表头数据
    getDetailexIsPrint() {
      const filterValArr = [
        'cardNumber',
        'userName',
        'departmentName',
        'dataMakeTime',
        'expenditure',
        'newBalance',
        'chargingType',
        'consumePlace',
        'terminalCode'
      ]
      let valArr = []
      let tHeader = []
      filterValArr.map(item => {
        if (this.formThead2[item].checked) {
          valArr.push(this.formThead2[item].prop)
          tHeader.push(this.formThead2[item].label)
        }
      })
      return { filterValArr: valArr, tHeader }
    },
    // 部门消费明细打印
    printDetailex() {
      let someJSONdata = this.detailslistExportlist
      const title = '部门消费明细表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getDetailexIsPrint()
      filterValArr.map((item, index) => {
        properties.push({
          displayName: tHeader[index],
          field: filterValArr[index]
        })
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    // 获取部门消费明细导出
    Detailexport2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { tHeader, filterValArr } = this.getDetailexIsPrint()
        const filterVal = filterValArr
        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename2 + nowtime
        })
      })
    },
    /**部门明细分页 */
    handleSizeChange2(val) {
      this.pageSize2 = val
      this.consumedetails()
    },
    handleCurrentChangepage2(val) {
      this.pageNum2 = val
      this.consumedetails()
    },
    checkboxChanged2() {
      this.$nextTick(() => {
        this.$refs['detailslist'].doLayout()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.department_consumption {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }
  .el-table th {
    display: table-cell !important;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    /deep/.el-form-item__label {
    }
    .el-form-item {
      margin-bottom: 5px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 250px;
    }
  }
  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;
    .searchmarigin {
      margin-left: 20px;
    }
  }
  .tabs_main {
    .page {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>